package com.hundsun.utils.impl;

import com.hundsun.model.ExcelToDbData;
import com.hundsun.utils.SqlExecutor;
import org.apache.commons.lang3.StringUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author jiangwj20966 2018/9/21
 */
public class SqlExecutorImpl implements SqlExecutor {

    private Connection connection;

    @Override
    public boolean executeInsert(ExcelToDbData data) {

        List<ExcelToDbData.DataInfo> dataInfos = data.getDataInfos();
        String tableName = data.getTableName();
        StringBuilder stringBuilder = new StringBuilder();
        if (StringUtils.isBlank(tableName)) {
            throw new IllegalStateException("未设置表名");
        }
        List<String> columnList = new ArrayList<>();
        List<String> valueList = new ArrayList<>();
        if (dataInfos == null || dataInfos.size() == 0) {
            throw new IllegalStateException("数据列表为空");
        }
        for (ExcelToDbData.DataInfo dataInfo : dataInfos) {
            columnList.add(dataInfo.getColumnName());
            valueList.add(dataInfo.getValue());
        }
        stringBuilder.append("INSERT INTO ").append(tableName).append(" (");
        for (String columnName : columnList) {
            stringBuilder.append(columnName).append(", ");
        }
        stringBuilder.deleteCharAt(stringBuilder.lastIndexOf(",")).append(") VALUES (");
        for (String value : valueList) {
            stringBuilder.append("?, ");
        }
        stringBuilder.deleteCharAt(stringBuilder.lastIndexOf(",")).append(")");
        try {

            PreparedStatement statement = connection.prepareStatement(stringBuilder.toString());
            int paramPosition = 1;
            for (String value : valueList) {
                statement.setObject(paramPosition++, value);
            }
            return statement.execute();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return false;
    }
}
